package com.erp.app.admin.companyMenu.web;

//JRE Classes
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.erp.app.admin.companyMenu.beans.CompanyMenuGroupVO;
import com.erp.app.admin.companyMenu.dao.CompanyMenuGroupDAO;
import com.erp.app.admin.companyMenu.ejb.CompanyMenuGroupPK;
import com.erp.app.admin.systemMenu.beans.SystemMenuGroupVO;
import com.erp.app.admin.systemMenu.beans.SystemMenuObjectVO;
import com.erp.app.admin.systemMenu.ejb.SystemMenuGroupPK;
import com.erp.app.common.ProjectConstants;
import com.erp.app.util.web.WebUtil;
import com.erp.framework.SimpleConstants;
import com.erp.framework.controller.action.SimpleMaintStyleAction;
import com.erp.framework.controller.form.SimpleMaintStyleForm;
import com.erp.framework.exceptions.CheckFieldLengthException;
import com.erp.framework.model.dao.ServiceLocator;
import com.erp.framework.model.delegate.SimpleSearchMaintStyleDelegate;
import com.erp.framework.model.pk.SimpleBasePk;
import com.erp.framework.model.vo.ChildList;
import com.erp.framework.model.vo.SimpleBaseVo;
import com.erp.framework.util.BeanUtil;
import com.erp.framework.util.CommonUtil;
import com.erp.framework.util.logger.Logger;
import com.erp.framework.util.user.User;

public class CompanyMenuMaintenanceAction extends SimpleMaintStyleAction {

    final private String actionAddCompanyMenuObject = "addCompanyMenuObject";
    final private String actionDelCompanyMenuObject = "delCompanyMenuObject";
    final private String DEFAULT_VISIBLE_LEVEL = "5";
    final private String DEFAULT_ENABLE_LEVEL = "5";

    protected void initPage(ActionMapping mapping, ActionForm formIn, HttpServletRequest request, HttpServletResponse response,
            ActionErrors errors) {
        super.initPage(mapping, formIn, request, response, errors);

        HttpSession session = request.getSession(false);
        CompanyMenuMaintenanceForm form = (CompanyMenuMaintenanceForm) formIn;

        String editExistInd = (String) session.getAttribute("MENU_EXIST_IND");
        System.out.println("MAINT ACTION, editExistInd=" + editExistInd);
        // if(editExistInd.equals(ProjectConstants.GENERIC_YES)) {
        try {

            CompanyMenuGroupPK cpk = (CompanyMenuGroupPK) session.getAttribute("MENU_PRIMARY_KEYS");
            // SystemMenuGroupPK pk = new
            // SystemMenuGroupPK(WebUtil.getAppropriateCompanyCode(session, ),
            // form.getGroupId(),
            // form.getMenuId());
            SystemMenuGroupPK pk = new SystemMenuGroupPK(WebUtil.getAppropriateCompanyCode(session,
                    ProjectConstants.SP_SHARE_COMPANY_MENU), cpk.getGroupId(), cpk.getMenuId());

            // System.out.println("pk = "+pk+", "+form.getGroupId()+",
            // "+form.getMenuId());
            SimpleSearchMaintStyleDelegate dg = getMasterMaintDelegate(session);
            // SystemMenuGroupVO menuGroupVO = (SystemMenuGroupVO)
            // dg.findByPrimaryKey(new SystemMenuGroupVO(), pk);

            SystemMenuGroupVO menuGroupVO = (SystemMenuGroupVO) dg.findByPrimaryKey(new SystemMenuGroupVO(), pk);

            form.setMenuGroupVO(menuGroupVO);
            // System.out.println("menuGroupVO = "+menuGroupVO);
            ChildList childList = menuGroupVO.getChilds(SystemMenuObjectVO.class);
            ArrayList rows = form.getMultiRows(0);
            // System.out.println("rows = "+rows.size());
            int i = 0;
            for (Iterator it = childList.iterator(); it.hasNext();) {
                SystemMenuObjectVO menuObjectVO = (SystemMenuObjectVO) it.next();
                CompanyMenuObjectRow row = null;
                // System.out.println("CompanyMenuObjectRow =
                // "+menuObjectVO.getPrimaryKey());
                if (rows != null) {
                    for (Iterator it2 = rows.iterator(); it2.hasNext();) {
                        CompanyMenuObjectRow currentRow = (CompanyMenuObjectRow) it2.next();
                        if (menuObjectVO.getMenuId().equals(currentRow.getMenuId())
                                && menuObjectVO.getGroupId().equals(currentRow.getGroupId())
                                && menuObjectVO.getObjectId().equals(currentRow.getObjectId())) {

                            row = currentRow;
                            break;
                        }
                    }
                }
                // System.out.println("row = "+row);
                if (row == null) {
                    row = new CompanyMenuObjectRow();

                    row.setCompanyCode(cpk.getCompanyCode());
                    row.setGroupId(cpk.getGroupId());
                    row.setMenuId(cpk.getMenuId());
                    row.setRoleGroupId(cpk.getRoleGroupId());
                    row.setObjectId(menuObjectVO.getObjectId());
                    row.setVisibleLevel(DEFAULT_VISIBLE_LEVEL);
                    row.setEnableLevel(DEFAULT_ENABLE_LEVEL);
                    row.setIsDelete("");
                    row.setObjectExistInd(ProjectConstants.GENERIC_NO);

                    form.addRow(row);
                    // System.out.println("form.addRow = "+row);
                } else {
                    row.setObjectExistInd(ProjectConstants.GENERIC_YES);
                }

                row.setMenuObjectVO(menuObjectVO);
            }
            // System.out.println("form = "+form);
        } catch (Exception e) {
            Logger.logExceptions(this, e);
        }
        // }
    }

    protected ActionForward handlePageEvent(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
            HttpServletResponse response, ActionErrors errors) {

        HttpSession session = request.getSession(false);
        
        
        CompanyMenuMaintenanceForm form = (CompanyMenuMaintenanceForm) formIn;
        String action = form.getPageEvent();
        action = CommonUtil.isEmpty(action) ? "" : action.trim();
        ActionForward actionForward = new ActionForward(mapping.getInput());

        String rb_status = CommonUtil.nullToString((String) session.getAttribute(getSessionSimpleMaintStatus()));
        System.out.println("handlePageEvent() action=" + action);
        System.out.println("handlePageEvent() isHandled=" + isHandled(request));

        if (!isHandled(request) && action.equalsIgnoreCase(actionAddCompanyMenuObject)) {
            setHandled(request);
            actionForward = processActionAddCompanyMenuObject(mapping, formIn, request, response, errors);
            saveToken(request);
        } else if (!isHandled(request) && action.equalsIgnoreCase(actionDelCompanyMenuObject)) {
            setHandled(request);
            actionForward = processActionDelCompanyMenuObject(mapping, formIn, request, response, errors);
            saveToken(request);
        }

        return actionForward;
    }

    protected ActionForward processActionAddCompanyMenuObject(ActionMapping mapping, ActionForm formIn,
            HttpServletRequest request, HttpServletResponse response, ActionErrors errors) {

        HttpSession session = request.getSession(false);
        CompanyMenuMaintenanceForm form = (CompanyMenuMaintenanceForm) formIn;
        ActionForward actionForward = new ActionForward(mapping.getInput());
        String action = CommonUtil.nullToString(form.getAction());
        User editingUser = (User) session.getAttribute(ProjectConstants.SESSION_USER);

        try {
            CompanyMenuObjectRow rowToAdd = new CompanyMenuObjectRow();
            form.setCurrIdx(0);

            rowToAdd.setCompanyCode(form.getCompanyCode());
            rowToAdd.setGroupId(form.getGroupId());
            rowToAdd.setMenuId(form.getMenuId());
            rowToAdd.setRoleGroupId(form.getRoleGroupId());
            rowToAdd.setIsDelete("");

            form.addRow(rowToAdd);
        } catch (Exception e) {
        	Logger.logExceptions(this, e);
        }

        return actionForward;
    }

    protected ActionForward processActionDelCompanyMenuObject(ActionMapping mapping, ActionForm formIn,
            HttpServletRequest request, HttpServletResponse response, ActionErrors errors) {

        HttpSession session = request.getSession(false);
        CompanyMenuMaintenanceForm form = (CompanyMenuMaintenanceForm) formIn;
        ActionForward actionForward = new ActionForward(mapping.getInput());
        String action = CommonUtil.nullToString(form.getAction());
        User editingUser = (User) session.getAttribute(ProjectConstants.SESSION_USER);

        // ArrayList rows = form.getMultiRows(0);
        ArrayList rows = form.getFinalRows();

        int idx = Integer.parseInt(form.getPageEventSrc());
        CompanyMenuObjectRow rowToEdit = (CompanyMenuObjectRow) rows.get(idx);
        rowToEdit.setIsDelete("checked");

        // form.setCurrIdx(0);
        form.setRow(idx, rowToEdit);

        return actionForward;
    }

    protected String getFunctionId() {
        return "companyMenuMaintenance.do";
    }

    protected Class getMasterFormClass() {
        return CompanyMenuMaintenanceForm.class;
    }

    protected Class getMasterVOClass() {
        return CompanyMenuGroupVO.class;
    }

    protected Class[] getChildRowClass() {
        return new Class[] { CompanyMenuObjectRow.class };
    }

    protected String[] getFolderChildIdxMapping() {
        // String[] folderChildIdx = new String[2];
        String[] folderChildIdx = new String[1];

        folderChildIdx[0] = "0";
        // folderChildIdx[1] = "1";

        return folderChildIdx;
        // return null;
    }

    protected String getSessionSimpleSearchStatus() {
        return ProjectConstants.SESSION_SIMPLE_SEARCH_STATUS;
    }

    protected String getSessionSimpleMaintStatus() {
        return ProjectConstants.SESSION_SIMPLE_MAINT_STATUS;
    }

    protected String getSessionSimpleMaintPk() {
        return ProjectConstants.SESSION_SIMPLE_MAINT_PK;
    }

    protected String getSessionSimpleMaintInitModel() {
        return ProjectConstants.SESSION_SIMPLE_MAINT_INIT_MODEL;
    }

    protected String getSessionSimpleMaintEditType() {
        return ProjectConstants.SESSION_SIMPLE_MAINT_EDIT_TYPE;
    }

    protected String getSessionMasterMaintDelegate() {
        return "SESSION_SM_DELEGATE";
    }

    protected String getSessionAlertAfterSave() {
        return ProjectConstants.SESSION_ALERT_AFTER_SAVE;
    }

    protected String getSessionAlertAfterDelete() {
        return ProjectConstants.SESSION_ALERT_AFTER_DELETE;
    }

    protected String getModuleName(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
            HttpServletResponse response) {
        return ProjectConstants.MOD_COMPANY_MENU_MAINT;
    }

    protected String getSessionReset() {
        return ProjectConstants.SESSION_SIMPLE_SEARCH_RESET;
    }

    protected SimpleBasePk getPk(ActionForm formIn, HttpServletRequest request) {
        CompanyMenuMaintenanceForm form = (CompanyMenuMaintenanceForm) formIn;
        CompanyMenuGroupPK pk = new CompanyMenuGroupPK(form.getCompanyCode(), form.getGroupId(), form.getMenuId(), form
                .getRoleGroupId());
        return pk;
    }

    protected boolean getKeepSearchResult() {
        return false;
    }

    protected String getSessionFolderIdx() {
        // return "cons.menu.maintenance.folderIdx";
        return "cons.remarkMaster.maintenance.folderIdx";

        // return Constants.SESSION_SIMPLE_MAIN_FOLDER_IDX;
    }

    protected void setSessionFolderIdx(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
            HttpServletResponse response) {
        HttpSession session = request.getSession(false);
        CompanyMenuMaintenanceForm form = (CompanyMenuMaintenanceForm) formIn;

        session.setAttribute(getSessionFolderIdx(), form.getFolderIdx());
    }

    protected SimpleBaseVo getInitialzedModel(ActionForm form, User editingUser) {
        return null;
    }

    protected void beforeValidate(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
            HttpServletResponse response, ActionErrors errors) {

        HttpSession session = request.getSession(false);
        
        

        CompanyMenuMaintenanceForm form = (CompanyMenuMaintenanceForm) formIn;
        ActionForward actionForward = new ActionForward(mapping.getInput());
        // User editingUser = (User)
        // session.getAttribute(Constants.SESSION_USER);

    }

//    protected void otherValidate(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
//            HttpServletResponse response, ActionErrors errors) {
//    }

    private int getNextSequence(Collection c, String seqPropertyName) throws Exception {

        int currentSeqNo, maxSeqNo = 1;
        Iterator iterator = c.iterator();
        while (iterator.hasNext()) {
            Object obj = iterator.next();
            String seqNo = (String) PropertyUtils.getSimpleProperty(obj, seqPropertyName);
            currentSeqNo = Integer.parseInt(seqNo);
            if (currentSeqNo >= maxSeqNo) {
                maxSeqNo = currentSeqNo + 1;
            }
        }
        return maxSeqNo;
    }

    protected void initAction(ActionMapping mapping, ActionForm formIn, HttpServletRequest request, HttpServletResponse response) {
    }

    protected ActionForward processActionSave(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
            HttpServletResponse response, ActionErrors errors) {
        HttpSession session = request.getSession(false);
        
        

        CompanyMenuMaintenanceForm form = (CompanyMenuMaintenanceForm) formIn;
        ActionForward actionForward = new ActionForward(mapping.getInput());
        User editingUser = (User) session.getAttribute(SimpleConstants.SESSION_USER);

        try {
            // validate form first

            if (CHECK_TOKEN) {
                if (!isTokenValid(request)) {
                    errors
                            .add(
                                    ActionErrors.GLOBAL_ERROR,
                                    new ActionError(
                                            "error.msg",
                                            "You may press the back button and then save this page! Please try to retrieve the data again and then change accordingly for saving!"));
                    saveErrors(request, errors);
                    saveToken(request);
                    return actionForward;
                }
            }

            // form.getFinalRows();

            beforeValidate(mapping, formIn, request, response, errors);

            form.validate(errors);

            otherValidate(mapping, formIn, request, response, errors);

            if (errors.size() == 0) {
                SimpleBaseVo model = (SimpleBaseVo) getMasterVOClass().newInstance();

                formToModel(form, model);

                afterFormToModel(mapping, formIn, request, response, errors, model);

                validateInput(errors, model);

                // save the model data
                if (errors.size() == 0) {

                    SimpleBaseVo originalModel = (SimpleBaseVo) form.getOldValues();
                    boolean modified = filterForEdited(model, originalModel, editingUser);
                    SimpleBasePk pk = null;

                    if (modified) {
                        if (CHECK_VERSION) {
                            setLastModifiedTime(model);
                        }

                        if (model.checkFieldLength()) {
                            SimpleSearchMaintStyleDelegate dg = getMasterMaintDelegate(session);
                            System.out.println("form.getPageMode()=" + form.getPageMode());
                            System.out.println("form.getExistInd()=" + form.getExistInd());
                            if (form.getPageMode().equals("create") || ProjectConstants.GENERIC_NO.equals(CommonUtil.nullToString(form.getExistInd()))) {
                                pk = dg.createMaster(model);
                            } else {
                                dg.updateMaster(model);
                                pk = (SimpleBasePk) model.getPrimaryKey();
                            }
                        }
                    }

                    session.setAttribute(getSessionAlertAfterSave(), ProjectConstants.GENERIC_YES);

                    form.setPageMode("modify");
                    session.setAttribute(getSessionSimpleMaintStatus(), "saved-edit");
                    
                    session.setAttribute(getSessionSimpleMaintPk(), pk);
                    setSessionFolderIdx(mapping, formIn, request, response);
                    actionForward = mapping.findForward("reload");
                }
                otherActionsAfterSave(mapping, formIn, request, response, errors);
            }
        } catch (CheckFieldLengthException cfe) {
            Logger.logExceptions(this, cfe);
            errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.msg", cfe.getMessage()));
        } catch (Exception e) {
            Logger.logExceptions(this, e);
            errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("exception.general", e.getMessage()));
        }

        return actionForward;
    }

    protected boolean filterForEdited(SimpleBaseVo currentVO, SimpleBaseVo originalVO, User editingUser) throws Exception {

        boolean modified = false;

        try {
            if (currentVO != null) {

                java.sql.Timestamp now = new java.sql.Timestamp(System.currentTimeMillis());

                currentVO.setLastModifiedTime(currentVO.getUpdateDate());

                if (originalVO != null) {
                    originalVO.setLastModifiedTime(originalVO.getUpdateDate());
                }

                // compares the child first
                ArrayList childsList = currentVO.getChildsList();
                Iterator iterator = childsList.iterator();
                while (iterator.hasNext()) {
                    ChildList currentChildList = (ChildList) iterator.next();
                    Class childType = currentChildList.getChildType();

                    Iterator iterator2 = currentChildList.iterator();
                    while (iterator2.hasNext()) {

                        SimpleBaseVo currentChildVO = (SimpleBaseVo) iterator2.next();
                        SimpleBaseVo originalChildVO = null;

                        if (currentChildVO.getIsExisting()) {
                            originalChildVO = originalVO == null ? null : originalVO.getChildVO(currentChildVO.getPrimaryKey(),
                                    childType);
                        }

                        // the (or) order must be in this order!!!
                        // don't revert the order
                        // if revert the filterForEdited will not be run if
                        // modified is true
                        modified = (this.filterForEdited(currentChildVO, originalChildVO, editingUser) || modified);

                    }
                }

                // compares header
                if (modified || originalVO == null || currentVO.getIsDelete() || !BeanUtil.isIdentical(originalVO, currentVO)) {

                    modified = true;

                    if (!currentVO.getIsExisting()) {
                        currentVO.setCreateUser(editingUser.getUserId());
                        // currentVO.setCreateDate(now);
                    } else {
                        currentVO.setIsDirty(true);
                        currentVO.setUpdateUser(editingUser.getUserId());
                        // currentVO.setUpdateDate(now);
                    }
                }
            }
        } catch (Exception e) {
            throw e;
        }

        return modified;
    }

    protected void beforeCreate(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
            HttpServletResponse response, ActionErrors errors) {

        HttpSession session = request.getSession(false);
        
        
        CompanyMenuMaintenanceForm form = (CompanyMenuMaintenanceForm) formIn;

        // String companyCode = WebUtil.getAppropriateCompanyCode(session,
        // Constants.SP_SHARE_COMPANY_MENU);
        // form.setCompanyCode(companyCode);
        // form.setGroupId(((User)session.getAttribute(Constants.SESSION_USER)).getGroupId());

        CompanyMenuGroupPK pk = (CompanyMenuGroupPK) session.getAttribute("MENU_PRIMARY_KEYS");
        form.setCompanyCode(pk.getCompanyCode());
        form.setGroupId(pk.getGroupId());
        form.setRoleGroupId(pk.getRoleGroupId());
        form.setMenuId(pk.getMenuId());
        form.setExistInd((String) session.getAttribute("MENU_EXIST_IND"));
    }

    protected String getMasterFormSessionName() {
        return "companyMenuMaintenanceForm";
    }

    protected void otherActionsAfterSave(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
            HttpServletResponse response, ActionErrors errors) {

        String crtMod = ProjectConstants.GENERIC_NO;
        String uptMod = ProjectConstants.GENERIC_NO;
        String delMod = ProjectConstants.GENERIC_NO;
        CompanyMenuMaintenanceForm form = (CompanyMenuMaintenanceForm) formIn;
        CompanyMenuGroupVO oldVO = (CompanyMenuGroupVO) form.getOldValues();
        if (form.getCreateLevel() != null) {
            if (form.getCreateLevel() != null && oldVO.getCreateLevel() != null
                    && !form.getCreateLevel().toString().equals(oldVO.getCreateLevel().toString())) {
                crtMod = ProjectConstants.GENERIC_YES;
            } else {
                crtMod = ProjectConstants.GENERIC_NO;
            }
        }
        if (form.getUpdateLevel() != null) {
            if (form.getUpdateLevel() != null && oldVO.getUpdateLevel() != null
                    && !form.getUpdateLevel().toString().equals(oldVO.getUpdateLevel().toString())) {
                uptMod = ProjectConstants.GENERIC_YES;
            } else {
                uptMod = ProjectConstants.GENERIC_NO;
            }
        }
        if (form.getDeleteLevel() != null) {
            if (form.getDeleteLevel() != null && oldVO.getDeleteLevel() != null
                    && !form.getDeleteLevel().toString().equals(oldVO.getDeleteLevel().toString())) {
                delMod = ProjectConstants.GENERIC_YES;
            } else {
                delMod = ProjectConstants.GENERIC_NO;
            }
        }
        Connection conn = null;
        CompanyMenuGroupDAO compDAO = new CompanyMenuGroupDAO();
        try {
            conn = conn = ServiceLocator.getInstance().getDSDBConnection();
            compDAO.updateMenuObject(form.getCompanyCode(), form.getGroupId(), form.getMenuId(), form.getRoleGroupId(), crtMod,
                    uptMod, delMod, conn);
        } catch (Exception e) {
        	Logger.logExceptions(this, e);
        } finally {
            try {
                if (conn != null)
                    conn.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    protected void setFormType(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
            HttpServletResponse response, ActionErrors errors){
        SimpleMaintStyleForm form = (SimpleMaintStyleForm)formIn;
        form.setFormType(ProjectConstants.FORM_TYPE_MAINT);
    }
    
}
